#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   mqttConfigDialog.py
@Time    :   2020/07/13 10:30:01
@Author  :   Xiong qiufeng
@Version :   1.0
@Contact :   1528399071@qq.com
@License :   (C)Copyright 2017-2018, Liugroup-NLPR-CASIA
@Desc    :   None
'''

import os
import copy
import json
from collections import OrderedDict

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

from ui.mqttConfig import Ui_Dialog
from .TableView import TableView 
from .ListView import ListView 

from common.libs.Log import logger
from common.libs.Helper import generateUUID

CONFIG_PATH = os.getcwd()+'/conf/mqtt.json'


class MqttConfigDialog(QDialog, Ui_Dialog):
    
    config = {}
    session = []
    select_session = None
    session_name = 'test'

    def __init__(self,parent=None):
        super(QDialog, self).__init__(parent)
        self.setupUi(self)
        self.setWindowTitle("会话配置")
        self.uiInit()
        self.signalInit()
        # 读取配置信息
        self.readConfig()
        # 更新列表
        self.listView.update([s['name'] for s in self.session])

    def uiInit(self):
        self.listView = ListView()
        self.verticalLayout_listview.addWidget(self.listView)
        # 推送表格
        self.publishTableView = TableView()
        self.publishTableView.setHeader(['主题','消息','服务质量'])
        self.verticalLayout_publish.addWidget(self.publishTableView)
        # 订阅表格
        self.subscribeTableView = TableView()
        self.subscribeTableView.setHeader(['主题','服务质量'])
        self.verticalLayout_subscribe.addWidget(self.subscribeTableView)

    def signalInit(self):
        self.listView.signal_clicked.connect(self.loadSessionByIndex)
        self.pushButton_clientid_generate.clicked.connect(lambda:self.lineEdit_clientid.setText('pc'+generateUUID()[0:8]))
        self.pushButton_publish_add.clicked.connect(lambda:self.publishTableView.addRow(["test","hello","0"]))
        self.pushButton_publish_delete.clicked.connect(self.publishTableView.deleteRow)
        self.pushButton_subscribe_add.clicked.connect(lambda:self.subscribeTableView.addRow(["test","0"]))
        self.pushButton_subscribe_delete.clicked.connect(self.subscribeTableView.deleteRow)
        self.pushButton_session_save.clicked.connect(self.addSession)
        self.pushButton_session_delete.clicked.connect(self.deleteSession)

    def getSessionNameList(self):
        return [s['name'] for s in self.session]

    def getSessionByIndex(self, index):
        return self.session[index]

    def loadSessionByIndex(self, index):
        """加载配置"""
        session = self.session[index]
        self.session_name = session['name']
        self.lineEdit_host.setText(session['host'])
        self.spinBox_port.setValue(int(session['port']))
        self.lineEdit_clientid.setText(session['client_id'])
        self.spinBox_timeout.setValue(int(session['timeout']))
        self.spinBox_keep_alive.setValue(int(session['keep_alive']))
        self.checkBox_auto_connect.setChecked(session['auto_connect'])
        publish = session['publish']
        subscribe = session['subscribe']
        self.publishTableView.clearData()
        self.subscribeTableView.clearData()
        for p in publish:
            self.publishTableView.addRow([p['topic'],p['msg'],p['qos']])
        for s in subscribe:
            self.subscribeTableView.addRow([s['topic'],s['qos']])

    def readConfig(self):
        """读取配置文件"""
        try:
            with open(CONFIG_PATH, 'r', encoding='utf-8') as f:
                self.config = json.loads(f.read(), object_pairs_hook=OrderedDict)
                self.session = self.config['session']
        except Exception as e:
            logger.info(e)
            QMessageBox.information(self,"提示","读取配置文件失败！", QMessageBox.Yes)
            return False

    def writeConfig(self):
        save = json.dumps(self.config, indent=4)
        with open(CONFIG_PATH, 'w', encoding='utf-8') as f:
            f.write(save)

    def addSession(self):
        try:
            session = {}
            session['host'] = self.lineEdit_host.text()
            session['port'] = self.spinBox_port.value()
            session['client_id'] = self.lineEdit_clientid.text()
            session['keep_alive'] = self.spinBox_keep_alive.value()
            session['timeout'] = self.spinBox_timeout.value()
            session['auto_connect'] = self.checkBox_auto_connect.isChecked()

            publish =  []
            for d in self.publishTableView.getRows():
                publish.append({ "topic":d[0], "msg":d[1], "qos":d[2] })
            session['publish'] = publish

            subscribe =  []
            for d in self.publishTableView.getRows():
                subscribe.append({ "topic":d[0], "qos":d[2] })
            session['subscribe'] = subscribe

            # 保存判断是否存在
            name, okPressed = QInputDialog.getText(self, "保存配置","名称:", QLineEdit.Normal, self.session_name)
            if okPressed:
                if name != '':
                    # session_list = copy.deepcopy(self.session)
                    isExist = False
                    index = 0
                    for i in range(0, len(self.session)):
                        if name == self.session[i]['name']:
                            isExist = True
                            index = i
                            break
                    if isExist == True:
                        button = QMessageBox.question(self,"询问","当前配置文件已存在，是否覆盖?",
                                    QMessageBox.Ok|QMessageBox.Cancel,QMessageBox.Ok)
                        if button == QMessageBox.Ok:
                            session['name'] = name
                            self.session[index] = session
                        elif button == QMessageBox.Cancel:
                            return
                    else:
                        session['name'] = name
                        self.session.append(session)
                else:
                    QMessageBox.information(self,"保存失败","名称不能为空!", QMessageBox.Yes)
                    return
            else:
                return
            self.config['session'] = self.session
            self.writeConfig()
            self.listView.update([s['name'] for s in self.session])
            QMessageBox.information(self,"提示","保存成功", QMessageBox.Yes)
            return True
        except Exception as e:
            logger.info(e)
            QMessageBox.information(self,"提示","保存失败, 文件被调用", QMessageBox.Yes)
            return False
        pass

    def deleteSession(self):
        index = self.listView.select_row
        if index >= 0:
            print(index)
            del self.session[index]
            self.config['session'] = self.session
            self.writeConfig()
            self.listView.update([s['name'] for s in self.session])

    def exec(self, index):
        if index >=0 :
            self.listView.setClicked(index)
            self.loadSessionByIndex(index)
        QDialog.exec(self)

